package org.jeecg.modules.workflow.framework.activiti.core.behavior.script.impl;

import com.boc.ewr.util.SysRoleEnum;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.runtime.ProcessInstance;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.util.collection.SetUtils;
import org.jeecg.modules.workflow.enums.definition.BpmTaskRuleScriptEnum;
import org.jeecg.modules.workflow.framework.activiti.core.behavior.script.BpmTaskAssignScript;
import org.jeecg.modules.workflow.service.task.BpmProcessInstanceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Set;

/**
 * @author : Wzz
 * @create : 2023-06- 13- 10:20
 * @desc : 分配给发起人二级行操作员审批的 Script 实现类
 */
@Component
public class BpmTaskAssignBranchHandlerScript implements BpmTaskAssignScript {

    @Resource
    @Lazy // 解决循环依赖
    private BpmProcessInstanceService bpmProcessInstanceService;

    @Autowired
    private ISysBaseAPI sysBaseAPI;

    @Override
    public Set<String> calculateTaskCandidateUsers(DelegateExecution execution) {
        ProcessInstance processInstance = bpmProcessInstanceService.getProcessInstance(execution.getProcessInstanceId());
        String userId = processInstance.getStartUserId();

        // 获取 业务部操作员 角色Id
        String roleId = sysBaseAPI.getRoleIdByRoleCode(SysRoleEnum.BRANCH_BUS_HANDLER.getCode());

        Set<String> adminHandlerByUserId = sysBaseAPI
                .getAdminUserIdByUserRole(userId, SetUtils.asSet(roleId));
        if (adminHandlerByUserId != null && adminHandlerByUserId.size() > 0) {
            return adminHandlerByUserId;
        }
        // 如果没有用户则返回管理员
        return SetUtils.asSet(sysBaseAPI.getLoginUserByUserName("admin").getId());
    }

    @Override
    public BpmTaskRuleScriptEnum getEnum() {
        return BpmTaskRuleScriptEnum.ADMIN_BRANCH_HANDLER;
    }
}
